using System.Runtime.CompilerServices;
using Awaiter;
using jQueryApi;

namespace YesPlayLove.Clusters
{
    [IgnoreNamespace]
    public class EmailMessage : EmailBase
    {
        private jQueryObject _header;
        private jQueryObject _messageBody;

        public EmailMessage(EmailCluster cluster) : base(cluster)
        {
        }

        public override EmailBase Build(bool active)
        {
            Initialize(active);

            Element
                .AddClass("Section LeftSide Message")
                .Hide()
                .Unbind("keyup.EmailMessage")
                .Bind("keyup.EmailMessage", delegate(jQueryEvent e) { CancelEvent(e); })
                ;

            if (active)
            {
                _header = jQuery.FromHtml("<div class='Header'/>")
                    .AppendTo(Element)
                    .Html(EmailTheme.MessageTitle)
                    ;

                jQuery.FromHtml("<span class='ActionBtn ReplyBtn'/>")
                    .AppendTo(_header)
                    .Html(EmailTheme.ReplyButton)
                    .Click(
                        delegate
                        {
                            new Await()
                                .AddAw(RebuildAw, false)
                                .AddDl(delegate(Await aw)
                                       {
                                           if (EmailBubbles != null)
                                           {
                                               jQueryObject inputEl = EmailBubbles.AppendReply(true).Fill("").FocusInput().Element;
                                               ScrollInViewAw(aw, inputEl);
                                           }
                                           else
                                               aw.Done();
                                       })
                                .Commit();
                        })
                    ;
            }

            _messageBody = jQuery.FromHtml("<p class='Body MessageBody'/>")
                .AppendTo(Element)
                ;

            return this;
        }

        public void RebuildAw(Await awp, bool active)
        {
            string msg = _messageBody.GetHtml();
            new Await()
                .AddAw(FadeOutAw, ThemeBase.FadeOut)
                .AddDx(delegate { Build(active).Fill(msg); })
                .AddAw(FadeInAw, ThemeBase.FadeIn)
                .Commit(awp);
        }

        public override EmailBase Fill(object msg)
        {
            _messageBody.Html((string) msg);
            return this;
        }
    }
}